package com.spring.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spring.entity.User;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyUtil {
	/**
	 * 根据当前时间生成字符串id
	 */
	public static String getStringID(){
		String id=null;
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS"); 
		id=sdf.format(date);
		return id;
	}
	/**
	 * 生成100000000内的随机数字符串
	 */
	public static String getRandom() {
		int n = (int)(Math.random()*100000000);
		return n + "";
	}

    /**
     * 判断token是否存在或过期
     * @param token
     * @return
     */
	public static boolean judgeToken(String token) throws IOException {
        if (token == null){
			return true;
        }else {
            User user = JwtToken.unsign(token, User.class);
            if (user == null){
                return true;
            }else {
                return false;
            }
        }
    }

	/**
	 * 获取文件扩展名
	 */
	public static String getFileExtendsName(String filenname) {
		int lastPointIndex = filenname.lastIndexOf(".");
		String extendsName = filenname.substring(lastPointIndex);
		return extendsName;
	}
	/**
	 * （汉字）字符串转换为UTF-8编码
	 */
	public static String toUTF8String(String str){
		StringBuffer sb = new StringBuffer();
		int len = str.length();
		for(int i = 0; i < len; i++){
			//遍历字符串
			char c = str.charAt(i);
			//Unicode 0-255 保持不变
			if(c >= 0 && c <= 255){
				sb.append(c);
			}else{//转换其它的字符
				byte b[];
				try {
					b = Character.toString(c).getBytes("UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					b = null;
				}
				//转换为无符号integer
				for(int j = 0; j < b.length; j ++){
					int k = b[j];
					if(k < 0){
						k &= 255;
					}
					//返回整数参数的字符串表示形式 作为十六进制（base16）中的无符号整数
					//该值以十六进制（base16）转换为ASCII数字的字符串
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	public static String getTime(){
		SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
		sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
		Date date = new Date();// 获取当前时间
		//System.out.println("现在时间：" + sdf.format(date)); // 输出已经格式化的现在时间（24小时制）
		return sdf.format(date);
	}

	/**
	 * 发起get请求的方法。
	 * @param url
	 * @return
	 */
	public static String GET(String url) {
		String result = "";
		BufferedReader in = null;
		InputStream is = null;
		InputStreamReader isr = null;
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.connect();
			Map<String, List<String>> map = conn.getHeaderFields();
			is = conn.getInputStream();
			isr = new InputStreamReader(is);
			in = new BufferedReader(isr);
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			// 异常记录
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (is != null) {
					is.close();
				}
				if (isr != null) {
					isr.close();
				}
			} catch (Exception e2) {
				// 异常记录
			}
		}
		return result;
	}

	/**
	 * 获取小程序端的code
	 * @param code
	 * @return
	 */
	public static JSONObject getSessionKeyOrOpenId(String code){
		//微信端登录code
		String wxCode = code;
		String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		Map<String,String> requestUrlParam = new HashMap<String, String>(  );
		//替换appid，appsecret，和code
		String requestUrl = WX_URL.replace("APPID", "wxde3f1afb7b27789d").//填写自己的appid
				replace("SECRET", "53bea54de83149417ab0806ea4ccfca8").replace("JSCODE", code).//填写自己的appsecret，
				replace("authorization_code", "authorization_code");

		//调用get方法发起get请求，并把返回值赋值给returnvalue
		String  returnvalue=GET(requestUrl);
		//测试用
		//System.out.println(requestUrl);//打印发起请求的url
		//System.out.println(returnvalue);//打印调用GET方法返回值
		//定义一个json对象。
		JSONObject convertvalue=new JSONObject();

		//将得到的字符串转换为json
		convertvalue=(JSONObject) JSON.parse(returnvalue);
		return convertvalue;
	}

    /**
     * 解密手机号
     * @param session_key
     * @param encryptedData
     * @param iv
     * @return
     */
    public JSONObject getPhoneNumber(String session_key,String encryptedData,String iv ){
        byte[] dataByte = Base64.decode(encryptedData);
        byte[] keyByte = Base64.decode(session_key);
        byte[] ivByte = Base64.decode(iv);
        try {
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    /**
     * 返回手机号
     * @param session_key
     * @param encryptedData
     * @param iv
     * @return
     */
    public String getPhone(String session_key,String encryptedData,String iv){
        JSONObject obj=getPhoneNumber(session_key,encryptedData,iv);
        System.out.println(obj);
        String phone=obj.get("phoneNumber").toString();
        return phone;

    }
}
